<?php
/**
 * 管理员操作
 * @desc 实现管理员的添加，管理，权限管理，删除等操作
 */
class Api_Admin extends PhalApi_Api {

    public function getRules() {
        return [
            'login'  => [
                'username' => ['name' => 'username', 'type' => 'string', 'min' => 4, 'max' => 12, 'require' => true, 'desc' => '用户名'],
                'passwrod' => ['name' => 'password', 'type' => 'string', 'min' => 6, 'max' => 16, 'require' => true, 'desc' => '密码'],

            ],
            'logout' => [
                'token' => ['name' => 'token', 'type' => 'string', 'min' => 12, 'max' => 12, 'require' => true, 'desc' => 'tokenID'],
            ],
            'lists'  => [
                'token' => ['name' => 'token', 'type' => 'string', 'min' => 12, 'max' => 12, 'require' => true, 'desc' => 'tokenID'],
                'keyword' => ['name' => 'keyword', 'type' => 'string',  'require' => false, 'desc' => '关键词'],
            ],
            'info'   => [
                'token'  => ['name' => 'token', 'type' => 'string', 'min' => 12, 'max' => 12, 'require' => true, 'desc' => 'tokenID'],
                'userid' => ['name' => 'userid', 'type' => 'string', 'require' => true, 'desc' => '用户id'],
            ],
            'delete' => [
                'token'  => ['name' => 'token', 'type' => 'string', 'min' => 12, 'max' => 12, 'require' => true, 'desc' => 'tokenID'],
                'userid' => ['name' => 'userid', 'type' => 'string', 'require' => true, 'desc' => '用户名'],
            ],
            'add'    => [
                'token'      => ['name' => 'token', 'type' => 'string', 'min' => 12, 'max' => 12, 'require' => true, 'desc' => 'tokenID'],
                'username'   => ['name' => 'username', 'type' => 'string', 'min' => 4, 'max' => 12, 'require' => true, 'desc' => '用户名'],
                'password'   => ['name' => 'password', 'type' => 'string', 'min' => 6, 'max' => 16, 'require' => true, 'desc' => '密码'],
                'repassword' => ['name' => 'repassword', 'type' => 'string', 'min' => 6, 'max' => 16, 'require' => true, 'desc' => '重复密码'],
                'nickname'   => ['name' => 'nickname', 'type' => 'string', 'min' => 1, 'max' => 16, 'require' => true, 'desc' => '用户昵称'],
                'email'      => ['name' => 'email', 'type' => 'email', 'require' => true, 'desc' => '用户邮箱'],
                'rules'      => ['name' => 'rules', 'type' => 'array', 'require' => false, 'default' => '[]', 'desc' => '用户权限'],
            ],
            'update' => [
                'token'      => ['name' => 'token', 'type' => 'string', 'min' => 12, 'max' => 12, 'require' => true, 'desc' => 'tokenID'],
                'userid'     => ['name' => 'userid', 'type' => 'string', 'require' => true, 'desc' => '用户id'],
                'password'   => ['name' => 'password', 'type' => 'string', 'min' => 6, 'max' => 16, 'require' => false, 'desc' => '密码'],
                'repassword' => ['name' => 'repassword', 'type' => 'string', 'min' => 6, 'max' => 16, 'require' => false, 'desc' => '重复密码'],
                'nickname'   => ['name' => 'nickname', 'type' => 'string', 'min' => 3, 'max' => 16, 'require' => false, 'desc' => '用户昵称'],
                'email'      => ['name' => 'email', 'type' => 'email', 'require' => false, 'desc' => '用户邮箱'],
                'rules'      => ['name' => 'rules', 'type' => 'array', 'require' => false, 'default' => '[]', 'desc' => '用户权限'],
            ],
        ];
    }

    /**
     * 管理员登陆
     * @desc 登陆接口
     * @return int ret HTTP状态码,200成功,其他失败
     * @return int code 操作码，0表示成功，1001表示用户不存在，1002密码错误，1003错误次数超限，1004账号状态异常
     * @return object info 用户信息对象
     * @return int info.id 用户ID
     * @return string info.username 用户名
     * @return string info.nickname 用户昵称
     * @return string info.email 用户邮箱
     * @return string info.lastlogintime 用户上次登陆时间
     * @return array info.rules 用户权限
     * @return string token 用户token 有效期2小时
     * @return string msg 提示信息
     */
    public function login() {
        // throw new PhalApi_Exception(T('asd'), 12);   //抛错
        // throw new PhalApi_Exception_BadRequest(T('asd'), 12);   //抛错  非法请求
        // throw new PhalApi_Exception_InternalServerError(T('asd'), 12);  //抛错  服务器运行错误

        $token = new Domain_Token();

        $rs = ['code' => 0, 'msg' => '', 'info' => []];

        $ClientIP = DI()->helper->getClientIp();
        $ipErrTimes = intval(DI()->cache->get("IPerrTime:" . $ClientIP));
        if ($ipErrTimes && $ipErrTimes > 10) {
            throw new PhalApi_Exception("登陆错误次数超过10次，请改IP被锁定12小时", 1003);
        }

        $domain = new Domain_Admin();
        $info = $domain->checkAdmin($this->username);


        if (empty($info)) {
            //写日志
            DI()->logger->debug('user not found', $this->username);
            // 错误次数缓存
            DI()->cache->set("IPerrTime:" . $ClientIP, $ipErrTimes + 1, 60 * 60 * 12);

            // 抛错
            DI()->response->setData(null);
            throw new PhalApi_Exception('用户不存在', 1001);
        }
        if ($info["password"] != md5($this->passwrod . $info["encryption"])) {
            //写日志
            DI()->logger->log('debug', '登陆密码错误', 'u:' . $this->username . ' pw:' . $this->passwrod . '||' . md5($this->passwrod . $info["encryption"]));

            // 错误次数缓存
            DI()->cache->set("IPerrTime:" . $ClientIP, $ipErrTimes + 1, 60 * 60 * 12);

            // 抛错
            DI()->response->setData(null);
            throw new PhalApi_Exception('密码错误', 1002);
        }
        // 返回数据处理
        unset($info['password']);
        unset($info['encryption']);
        $info["rules"]=@json_decode($info["rules"]);

        //更新登陆时间
        $domain->updatelastlogintime($this->username);
        //设置token
        $userToken = $token->create($info);

        // 返回数据处理
        $rs['info'] = $info;
        $rs['token'] = $userToken;
        return $rs;
    }



    /**
     * 管理员列表
     * @desc
     * @return int ret HTTP状态码,200:成功,1003:token失效
     * @return int userid 用户id
     * @return string nickname 用户昵称
     * @return email email 用户邮箱
     * @return string username 用户名
     * @return array rules 用户权限
     * @return date lastlogintime 用户最后登录时间
     * @return string msg 提示信息
     */
    public function lists() {

        $db = new Domain_Admin();
        return $db->getlist($this->keyword);
    }

    /**
     * 管理员资料获取
     * @desc
     * @return int ret HTTP状态码,200:成功,1003:token失效
     * @return int userid 用户id
     * @return string nickname 用户昵称
     * @return email email 用户邮箱
     * @return string username 用户名
     * @return array rules 用户权限
     * @return date lastlogintime 用户最后登录时间
     * @return string msg 提示信息
     */
    public function info() {



        $db = new Domain_Admin();
        $info = $db->getAdminById($this->userid);
        if ($info) {
            unset($info['password']);
            unset($info['encryption']);
            $info["rules"]=@json_decode($info["rules"]);
        }

        return $info;
    }

    /**
     * 添加管理员
     * @desc
     * @return int ret HTTP状态码,200:成功,1003:token失效
     * @return array data 列表
     * @return string msg 提示信息
     */
    public function add() {



        if ($this->password != $this->repassword) {
            DI()->response->setData(null);
            throw new PhalApi_Exception_BadRequest('重复密码错误');
        }



        $db = new Domain_Admin();

        $info = $db->add($this->username, $this->password, $this->nickname, $this->email,@json_encode($this->rules));
        if(!$info){
            throw new PhalApi_Exception('添加账号失败', 1005);
        }
        unset($info['password']);
        unset($info['encryption']);
        $info["rules"]=@json_decode($info["rules"]);
        return $info;
    }

    /**
     * 更新管理员资料
     * @desc
     * @return int ret HTTP状态码,200:成功,1005:更新资料失败
     * @return isupdate data 更新后的信息
     * @return string msg 提示信息
     */
    public function update() {



        if ($this->password == null && $this->nickname == null && $this->email == null&& $this->rules == null) {
            DI()->response->setData(null);
            throw new PhalApi_Exception_BadRequest('参数错误，必须有可修改资料');
        }
        if (($this->password || $this->repassword) && $this->repassword != $this->password) {
            DI()->response->setData(null);
            throw new PhalApi_Exception_BadRequest('重复密码错误');
        }
        $db = new Domain_Admin();

        $info = $db->update($this->userid, $this->password, $this->nickname, $this->email,@json_encode($this->rules));

        if (!$info) {
            DI()->response->setData(null);
            throw new PhalApi_Exception('更新资料失败', 1005);
        }

        return array(
            "isupdate"=>($info==1)
        );
    }

    /**
     * 删除管理员
     * @desc
     * @return int ret HTTP状态码,200:成功,1003:token失效
     * @return boolean data.isdelete 删除状态:true删除成功，false删除失败
     * @return string msg 提示信息
     */
    public function delete() {

        $token = new Domain_Token();
        $user = $token->check($this->token);
        if ($user['id'] == $this->userid) {
            DI()->response->setData(null);
            throw new PhalApi_Exception_BadRequest('不能删除自己的账号');
        }
        $db = new Domain_Admin();
        $info = $db->delete($this->userid);

        return [
            "isdelete" => ($info == 1)
        ];

    }

    /**
     * 管理员登出
     * @desc 登出接口
     * @return boolean data.islogout 退出状态:true退出成功，false退出失败
     * @return string msg 提示信息
     */
    public function logout() {
        $token = new Domain_Token();
        return [
            "islogout" => $token->remove($this->token)
        ];

    }
}
